package ftp.action;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.apache.commons.net.ftp.FTPClient;

import fpt.dao.FtpConfiglangDAO;
import fpt.dao.FtpConnectSQLITE;
import fpt.dao.FtpUserDAO;
import fpt.util.FTPUtil;
import fpt.util.UtilInitLang;
import ftp.pojo.FtpConfiglang;
import ftp.pojo.FtpConnect;
import ftp.pojo.FtpUser;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.LayoutInflater.Factory;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class LogoutActivity extends Activity {

	class PInfo {
		private String appname = "";
		@SuppressWarnings("unused")
		private String pname = "";
		private String versionName = "";
		private int versionCode = 0;
	}
	public int co=0;
	EditText username,pass,port;
	private Bundle alllangs = new Bundle();
	String typeLang = "EN";
	UtilInitLang utilang = new UtilInitLang();
	private boolean read = true;
	ImageView imageVN,imageEN,imageKR;
	FtpUser emp = new FtpUser();
	public FTPClient mFTPClient = null;
	FtpConnect ftp=new FtpConnect();
	Button btLogin;
	String host="";

	//auto update
	public int VersionCode;
	public String VersionName="";
	public String ApkName ;
	public String AppName ;
	public String BuildVersionPath="";
	public String urlpath ;
	public String PackageName;
	public String InstallAppPackageName;
	public String Text="";
	Bundle lang=new Bundle();
	
	// TODO hongmophi
	private Spinner lstSpinnerHost;
	private List<FtpConnect> lstConnect = new ArrayList<FtpConnect>();

	private FtpConnectSQLITE ftpConnectSQLITE;
	
	public  String ahostname="";
	public  String aport="";
	public  String ausername="";
	public  String apassword="";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		Text= "New".toString();

		ApkName = "FtpClient.apk";//"Test1.apk";// //"DownLoadOnSDcard_01.apk"; //      
		AppName="FtpClient";
		BuildVersionPath = "http://14.63.215.15/ftp_version.txt".toString();
		PackageName = "package:com.SelfInstall01".toString(); //"package:com.Test1".toString();
		urlpath = "http://14.63.215.15/" + ApkName.toString();


		GetVersionFromServer(BuildVersionPath); 
		
		 readFile();
	     lang = this.getAlllangs().getBundle(typeLang);

		if(checkInstalledApp(AppName.toString()) == true)
		{   
			Toast.makeText(getApplicationContext(), lang.getString("appfound")+" " + AppName.toString(), Toast.LENGTH_SHORT).show();

		}else{
			Toast.makeText(getApplicationContext(), lang.getString("appnotfound")+" "+ AppName.toString(), Toast.LENGTH_SHORT).show();          

		}
        
        setContentView(R.layout.main);
        ftpConnectSQLITE = new FtpConnectSQLITE(this);
		ftpConnectSQLITE.open();
		
		username =(EditText)findViewById(R.id.userName);
		pass =(EditText)findViewById(R.id.pass);

		initAttribute();        

		imageVN = (ImageView)findViewById(R.id.imageViewVN);
		imageEN = (ImageView)findViewById(R.id.imageViewUK);
		imageKR = (ImageView)findViewById(R.id.imageViewKR);

		imageVN.setOnClickListener(processImageVN);
		imageEN.setOnClickListener(processImageEN);
		imageKR.setOnClickListener(processImageKR);

		btLogin.setOnClickListener(loginbtn);
    }
    
    private OnClickListener loginbtn = new OnClickListener() {


		public void onClick(View v) {
			try{
				FTPUtil.HOST=host;

				FTPUtil.PORT=Integer.parseInt(port.getText().toString());

				FTPUtil.USER=username.getText().toString();
				FTPUtil.PASS=pass.getText().toString();

				if (FTPUtil.connects()) {

					ftp.setHostname(host);
					ftp.setPort(port.getText().toString());
					ftp.setPassword(pass.getText().toString());
					ftp.setUsername(username.getText().toString());					
					startActivity();
				} else {
					openDialogError();
				}
			}catch (Exception e) {
				e.printStackTrace();
			} 
		}

	}; 

	private void openDialogError() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(lang.getString("warning"));
		builder.setMessage(lang.getString("rploginfail"));
		builder.setCancelable(false);
		builder.setPositiveButton(lang.getString("ok"), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.show();
	}

	private void startActivity() {

		Intent ii = new Intent(this, MainActivity2.class);
		ii.putExtra("lang", typeLang);
		ii.putExtras(alllangs);		
		ii.putExtra("ftp", ftp);
		startActivity(ii);
	}

	public FtpUser checkLogin(String username, String pass) {
		FtpUserDAO lg = new FtpUserDAO();
		FtpUser emp = lg.checkLogin(username, pass);
		return emp;
	}
	public void initLangue(){
		
		TextView thost=(TextView)findViewById(R.id.host);
		thost.setText(lang.getString("hostname"));

		TextView tport=(TextView)findViewById(R.id.Port);
		tport.setText(lang.getString("port"));		

		TextView tendn = (TextView) findViewById(R.id.tendn);
		tendn.setText(lang.getString("username"));

		TextView pw = (TextView) findViewById(R.id.matkhau);
		pw.setText(lang.getString("password"));
		
		btLogin.setText(lang.getString("connect"));
		
	}
	public void initAttribute() {
//		Display display = getWindowManager().getDefaultDisplay(); 
//		int width = display.getWidth()*3/10;
		
		
		TextView thost=(TextView)findViewById(R.id.host);
		thost.setText(lang.getString("hostname"));

		TextView tport=(TextView)findViewById(R.id.Port);
		tport.setText(lang.getString("port"));

		port = (EditText) findViewById(R.id.txtPort);

		TextView t = (TextView) findViewById(R.id.tendn);
		t.setText(lang.getString("username"));

		TextView t2 = (TextView) findViewById(R.id.matkhau);
		t2.setText(lang.getString("password"));

		btLogin = (Button) findViewById(R.id.btLogin);
		btLogin.setText(lang.getString("connect"));

		lstSpinnerHost = (Spinner)findViewById(R.id.spinnerhost);
		lstConnect = ftpConnectSQLITE.getAllConnect();
		ArrayAdapter<FtpConnect> adapter = new ArrayAdapter<FtpConnect>(this,
				android.R.layout.simple_spinner_dropdown_item,lstConnect);
		lstSpinnerHost.setAdapter(adapter);
		lstSpinnerHost.setOnItemSelectedListener(processSpinner);

	}

	private void readFile(){		
		typeLang="EN";
		try {

			FileInputStream fr = openFileInput("user.txt");
			Scanner scanner = new Scanner(fr);
			typeLang=scanner.next().trim();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Bundle getAlllangs() {
		if (isRead()) {
			FtpConfiglangDAO lang = new FtpConfiglangDAO();
			Bundle resultVN = new Bundle();
			Bundle resultEN = new Bundle();
			Bundle resultKR = new Bundle();
			try {
				ArrayList<FtpConfiglang> arr = lang.allLang();
				for (int i = 0; i < arr.size(); i++) {
					resultVN.putString(arr.get(i).getIdkey(), arr.get(i).getVn());
					resultEN.putString(arr.get(i).getIdkey(), arr.get(i).getEn());
					resultKR.putString(arr.get(i).getIdkey(), arr.get(i).getKr());
				};
			} catch (Exception E) {
				E.printStackTrace();
			}
			alllangs.putBundle("VN", resultVN);
			alllangs.putBundle("EN", resultEN);
			alllangs.putBundle("KR", resultKR);
		}
		setRead(false);
		return alllangs;
	}

	public boolean isRead() {
		return read;
	}
	public void setRead(boolean read) {
		this.read = read;
	}

	public OnClickListener processImageVN = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			typeLang = "VN";
			initLangue();
		}
	};

	public OnClickListener processImageEN = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			typeLang = "EN";
			initLangue();
		}
	};

	public OnClickListener processImageKR = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			typeLang = "KR";
			initLangue();
		}
	};

	public OnItemSelectedListener processSpinner = new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
			ftp = (FtpConnect)lstSpinnerHost.getItemAtPosition(arg2);
			host = ftp.getHostname();
			port.setText(ftp.getPort());
			username.setText(ftp.getUsername());
			pass.setText(ftp.getPassword());
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			Log.d(getApplicationContext().getPackageName(), "Select Item :"
					+ "Nothing");
			typeLang = "EN";			
		}
	};

	protected void showPopupDelete() {
		AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		helpBuilder.setTitle(lang.getString("titledelete"));
		helpBuilder.setMessage(lang.getString("deleteerror"));
		helpBuilder.setPositiveButton(lang.getString("ok"),
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				ftpConnectSQLITE.deleteFtp(ftp);
				Intent intent = new Intent(
						LogoutActivity.this,
						LogoutActivity.class);

				startActivity(intent);
				finish();
			}
		});

		helpBuilder.setNegativeButton(lang.getString("cancel"),
				new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				// Do nothing
			}
		});

		AlertDialog helpDialog = helpBuilder.create();
		helpDialog.show();
	}


	private Boolean checkInstalledApp(String appName){
		return getPackages(appName);    
	}

	// Get Information about Only Specific application which is Install on Device.
	public String getInstallPackageVersionInfo(String appName) 
	{
		String InstallVersion = "";     
		ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
		final int max = apps.size();
		for (int i=0; i<max; i++) 
		{
			//apps.get(i).prettyPrint();        
			if(apps.get(i).appname.toString().equals(appName.toString()))
			{
				InstallVersion = lang.getString("installversioncode")+": "+ apps.get(i).versionCode+
				" "+lang.getString("versionname")+": "+ apps.get(i).versionName.toString();
				break;
			}
		}

		return InstallVersion.toString();
	}
	private Boolean getPackages(String appName) 
	{
		Boolean isInstalled = false;
		ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
		final int max = apps.size();
		for (int i=0; i<max; i++) 
		{

			if(apps.get(i).appname.toString().equals(appName.toString()))
			{
				if(VersionCode <= apps.get(i).versionCode)
				{
					isInstalled = false;

				}    
				if(VersionCode > apps.get(i).versionCode)
				{
					isInstalled = true;

					DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() 
					{
						@Override
						public void onClick(DialogInterface dialog, int which) {
							switch (which)
							{
							case DialogInterface.BUTTON_POSITIVE:
								DownloadOnSDcard();
								InstallApplication();
								UnInstallApplication(PackageName.toString());

								break;

							case DialogInterface.BUTTON_NEGATIVE:
								break;
							}
						}
					};

					AlertDialog.Builder builder = new AlertDialog.Builder(this);
					builder.setMessage(lang.getString("youhavenewversion")).setPositiveButton(lang.getString("install"), dialogClickListener)
					.setNegativeButton(lang.getString("cancel"), dialogClickListener).show();              
				}
			}
		}

		return isInstalled;
	}
	private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) 
	{       
		ArrayList<PInfo> res = new ArrayList<PInfo>();        
		List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);

		for(int i=0;i<packs.size();i++) 
		{
			PackageInfo p = packs.get(i);
			if ((!getSysPackages) && (p.versionName == null)) {
				continue ;
			}
			PInfo newInfo = new PInfo();
			newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
			newInfo.pname = p.packageName;
			newInfo.versionName = p.versionName;
			newInfo.versionCode = p.versionCode;
			res.add(newInfo);
		}
		return res; 
	}


	public void UnInstallApplication(String packageName)// Specific package Name Uninstall.
	{
		Uri packageURI = Uri.parse(packageName.toString());
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		startActivity(uninstallIntent); 
	}
	public void InstallApplication()
	{   
		Uri packageURI = Uri.parse(PackageName.toString());
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW, packageURI);

		intent.setDataAndType
		(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/"  + ApkName.toString())), "application/vnd.android.package-archive");

		startActivity(intent);  
	}
	public void GetVersionFromServer(String BuildVersionPath)
	{
		URL u;
		try {
			u = new URL(BuildVersionPath.toString());

			HttpURLConnection c = (HttpURLConnection) u.openConnection();           
			c.setRequestMethod("GET");
			c.setDoOutput(true);
			c.connect();

			InputStream in = c.getInputStream();

			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024]; //that stops the reading after 1024 chars..

			int len1 = 0;
			while ( (len1 = in.read(buffer)) != -1 ) 
			{               
				baos.write(buffer,0, len1); // Write Into ByteArrayOutputStream Buffer.
			}

			String temp = "";     
			String s = baos.toString();// baos.toString(); contain Version Code = 2; \n Version name = 2.1;

			for (int i = 0; i < s.length(); i++)
			{               
				i = s.indexOf("=") + 1; 
				while (s.charAt(i) == ' ') // Skip Spaces
				{
					i++; // Move to Next.
				}
				while (s.charAt(i) != ';'&& (s.charAt(i) >= '0' && s.charAt(i) <= '9' || s.charAt(i) == '.'))
				{
					temp = temp.toString().concat(Character.toString(s.charAt(i))) ;
					i++;
				}
				//
				s = s.substring(i); // Move to Next to Process.!
				temp = temp + " "; // Separate w.r.t Space Version Code and Version Name.
			}
			String[] fields = temp.split(" ");// Make Array for Version Code and Version Name.

			VersionCode = Integer.parseInt(fields[0].toString());// .ToString() Return String Value.
			VersionName = fields[1].toString();

			System.out.println("Vesiom code _ " + VersionCode);
			System.out.println("Vesion name _ " + VersionName);
			baos.close();
		}
		catch (MalformedURLException e) {
			Toast.makeText(getApplicationContext(), "Error." + e.getMessage(), Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		} catch (IOException e) {           
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "Error." + e.getMessage(), Toast.LENGTH_SHORT).show();
		}
	}// Method End.

	// Download On My Mobile SDCard or Emulator.
	public void DownloadOnSDcard()
	{
		try{
			URL url = new URL(urlpath.toString()); // Your given URL.

			HttpURLConnection c = (HttpURLConnection) url.openConnection();
			c.setRequestMethod("GET");
			c.setDoOutput(true);
			c.connect(); // Connection Complete here.!

			String PATH = Environment.getExternalStorageDirectory() + "/download/";
			File file = new File(PATH); // PATH = /mnt/sdcard/download/
			if (!file.exists()) {
				file.mkdirs();
			}
			File outputFile = new File(file, ApkName.toString());           
			FileOutputStream fos = new FileOutputStream(outputFile);

			InputStream is = c.getInputStream(); // Get from Server and Catch In Input Stream Object.

			byte[] buffer = new byte[1024];
			int len1 = 0;
			while ((len1 = is.read(buffer)) != -1) {
				fos.write(buffer, 0, len1); // Write In FileOutputStream.
			}
			fos.close();
			is.close();//till here, it works fine - .apk is download to my sdcard in download file.
		} 
		catch (IOException e) 
		{
			Toast.makeText(getApplicationContext(), "Error! " +
					e.toString(), Toast.LENGTH_LONG).show();
		}           
	}
	
	// show popup add host
	public void showpopupaddhostFromAndroid(){
		LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);          
		final View textEntryView = inflater.inflate(R.layout.addhost, null);

//		Bundle lang = this.getAlllangs().getBundle(typeLang);

		final EditText txtHostname = (EditText) textEntryView.findViewById(R.id.txtAddHost);
		txtHostname.setText(ahostname);
		final EditText txtPort = (EditText) textEntryView.findViewById(R.id.txtAddPort);
		txtPort.setText(aport);
		final EditText txtUserName = (EditText) textEntryView.findViewById(R.id.txtUserName);
		txtUserName.setText(ausername);
		final EditText txtPass = (EditText) textEntryView.findViewById(R.id.txtPass);
		txtPass.setText(apassword);
		final TextView hostname = (TextView) textEntryView.findViewById(R.id.addhostName);
		final TextView vport = (TextView) textEntryView.findViewById(R.id.aaPort);
		final TextView vus = (TextView) textEntryView.findViewById(R.id.addUsername);
		final TextView vps = (TextView) textEntryView.findViewById(R.id.addPass);

		hostname.setText(lang.getString("hostname"));
		vport.setText(lang.getString("port"));
		vus.setText(lang.getString("username"));
		vps.setText(lang.getString("password"));

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(lang.getString("addhost"));
		builder.setView(textEntryView);
		co=0;
		builder.setPositiveButton(lang.getString("ok"), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				try {
					if(!txtHostname.getText().toString().equals("") && !txtPort.getText().toString().equals("")
							&& !txtUserName.getText().toString().equals("") && !txtPass.getText().toString().equals("")){
						ahostname="";
						aport="";
						ausername="";
						apassword="";
						
						ftpConnectSQLITE.createFtpConnect(txtHostname.getText().toString(), txtPort.getText().toString(), txtUserName.getText().toString(),
								txtPass.getText().toString());

						Intent intent = new Intent(LogoutActivity.this, LogoutActivity.class);
						startActivity(intent);
					}
					else if(txtHostname.getText().toString().equals("") || txtPort.getText().toString().equals("")
							|| txtUserName.getText().toString().equals("") || txtPass.getText().toString().equals("")){

						ahostname = txtHostname.getText().toString();
						aport = txtPort.getText().toString();
						ausername = txtUserName.getText().toString();
						apassword = txtPass.getText().toString();

						Toast.makeText(getApplicationContext(),lang.getString("isempty"), Toast.LENGTH_LONG).show();
						showpopupaddhostFromAndroid();
					}
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		);
		builder.setNegativeButton(lang.getString("cancel"), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		AlertDialog alert = builder.create();
		alert.show();
	}
	
	// edit host 
	public void showpopupedithostfromAdroid(){
		LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);          
		final View textEntryView = inflater.inflate(R.layout.edithost, null);

//		Bundle lang = this.getAlllangs().getBundle(typeLang);

		final EditText txtHostname = (EditText) textEntryView.findViewById(R.id.txteditHost);
		txtHostname.setText(ahostname);
		final EditText txtPort = (EditText) textEntryView.findViewById(R.id.txteditPort);
		txtPort.setText(aport);
		final EditText txtUserName = (EditText) textEntryView.findViewById(R.id.txteditUserName);
		txtUserName.setText(ausername);
		final EditText txtPass = (EditText) textEntryView.findViewById(R.id.txteditPass);
		txtPass.setText(apassword);

		txtHostname.setText(ftp.getHostname());
		txtPort.setText(String.valueOf(ftp.getPort()));
		txtUserName.setText(ftp.getUsername());
		txtPass.setText(ftp.getPassword());

		final TextView hostname = (TextView) textEntryView.findViewById(R.id.edithostName);
		final TextView vport = (TextView) textEntryView.findViewById(R.id.editPort);
		final TextView vus = (TextView) textEntryView.findViewById(R.id.editUsername);
		final TextView vps = (TextView) textEntryView.findViewById(R.id.editPass);

		hostname.setText(lang.getString("hostname"));
		vport.setText(lang.getString("port"));
		vus.setText(lang.getString("username"));
		vps.setText(lang.getString("password"));

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(lang.getString("edithost"));
		builder.setView(textEntryView);
		co=0;
		builder.setPositiveButton(lang.getString("ok"), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if( !txtHostname.getText().toString().equals("") && !txtPort.getText().toString().equals("")
						&& !txtUserName.getText().toString().equals("") && !txtPass.getText().toString().equals("")){
					ahostname ="";
					aport = "";
					ausername = "";
					apassword = "";
					
					ftp.setHostname(txtHostname.getText().toString());
					ftp.setPort(txtPort.getText().toString());
					ftp.setUsername(txtUserName.getText().toString());
					ftp.setPassword(txtPass.getText().toString());
					
					ftpConnectSQLITE.updateFtp(ftp);
					
					Intent intent = new Intent(LogoutActivity.this, LogoutActivity.class);
					startActivity(intent);
				}
				else if(txtHostname.getText().toString().equals("") || txtPort.getText().toString().equals("")
						|| txtUserName.getText().toString().equals("") || txtPass.getText().toString().equals("")){
					ahostname = txtHostname.getText().toString();
					aport = txtPort.getText().toString();
					ausername = txtUserName.getText().toString();
					apassword = txtPass.getText().toString();
					
					Toast.makeText(getApplicationContext(),lang.getString("isempty"), Toast.LENGTH_LONG).show();
					showpopupedithostfromAdroid();
				} 

				
			}
		});

		builder.setNegativeButton(lang.getString("cancel"), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		AlertDialog alert = builder.create();
		alert.show();	 
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = new MenuInflater(getApplicationContext());
		if(lang.equals("EN")){
			inflater.inflate(R.menu.option_main_menu_en, menu);
		}else if(lang.equals("VN")){
			inflater.inflate(R.menu.option_main_menu_vn, menu);
		}else{
			inflater.inflate(R.menu.option_main_menu_kr, menu);
		}

		setMenuBackground();
		return true;

	}
	
	protected void setMenuBackground(){
		Log.d("", "Enterting setMenuBackGround");  
		getLayoutInflater().setFactory( new Factory() {  


			@Override
			public View onCreateView(String name, Context context,
					AttributeSet attrs) {
				if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {  

					try { 
						LayoutInflater f = getLayoutInflater();  
						final View view = f.createView( name, null, attrs );  
						new Handler().post( new Runnable() {  
							public void run () {  
								view.setBackgroundColor(Color.parseColor("#506256"));
							}  
						} );  
						return view;  
					}  
					catch ( InflateException e ) {}  
					catch ( ClassNotFoundException e ) {}  
				}  
				return null;  

			}  
		});  
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(lang.equals("VN")){
			switch (item.getItemId()) {
			case R.id.menuaddhostvn:
				showpopupaddhostFromAndroid();
				return true;
			case R.id.menuedithostvn:
				showpopupedithostfromAdroid();
				return true;
			case R.id.menudeletehostvn:
				showPopupDelete();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}else if(lang.equals("KR")){
			switch (item.getItemId()) {
			case R.id.menuaddhostkr:
				showpopupaddhostFromAndroid();
				return true;
			case R.id.menuedithostkr:
				showpopupedithostfromAdroid();
				return true;
			case R.id.menudeletehostkr:
				showPopupDelete();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}else{
			switch (item.getItemId()) {
			case R.id.menuaddhost:
				showpopupaddhostFromAndroid();
				return true;
			case R.id.menuedithost:
				showpopupedithostfromAdroid();
				return true;
			case R.id.menudeletehost:
				showPopupDelete();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}
	}
	@Override
	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(lang.getString("exitapp"));
		builder.setMessage(lang.getString("questionexitapp"));
		builder.setPositiveButton(lang.getString("ok"),new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				LogoutActivity.this.moveTaskToBack(true);
				android.os.Process.killProcess(android.os.Process.myPid());
				android.os.Process.sendSignal(android.os.Process.myPid(), android.os.Process.SIGNAL_KILL);
			}
		});
		
		builder.setNegativeButton(lang.getString("cancel"), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
			}
		});
		
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}
}
